package com.utils.picasso;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;

import com.gxpt.app.AppUtils;
import com.squareup.picasso.Transformation;
import com.utils.logger.Logger;

/**
 * Created by dufeng on 2017/5/11.
 */

public class ProportionTransform implements Transformation {

    private static final String KEY = "proportionTransformation";

    Context context;
    public ProportionTransform(Context contex){
        this.context = contex;
    }

    @Override
    public Bitmap transform(Bitmap source) {

        int targetWidth = source.getWidth();

        if(source.getWidth()==0){
            return source;
        }


        int bwidth = source.getWidth();
        int bHeight = source.getHeight();
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();


        int width = displayMetrics.widthPixels-40;
//        int heightpx = displayMetrics.heightPixels;

//        int maxHeight = AppUtils.dp2px(this.context, 300);
        int maxHeight = AppUtils.dp2px(this.context, bHeight);
        int height = (int) ((float) width/bwidth * bwidth);
        if (height > maxHeight) height = maxHeight;

        Logger.i("width = "+width+"  height = "+height);

        Bitmap result = Bitmap.createScaledBitmap(source, width, height, false);
        if (result != source) {
            // Same bitmap is returned if sizes are the same
            source.recycle();
        }
        return result;



//        //如果图片小于设置的宽度，则返回原图
//        if(source.getWidth()<targetWidth){
//            return source;
//        }else{
//            //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
//            double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
//            int targetHeight = (int) (targetWidth * aspectRatio);
//            if (targetHeight != 0 && targetWidth != 0) {
//                Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
//                if (result != source) {
//                    // Same bitmap is returned if sizes are the same
//                    source.recycle();
//                }
//                return result;
//            } else {
//                return source;
//            }
//        }
    }

    @Override
    public String key() {
        return KEY;
    }

}
